require('./connect')
const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
  age: {
    type: Number,
    min: 10,
    max: 100
  },
  email: {
    type: String,
    validate: {
      validator: function (v) {
        return v && v.includes('@')
      },
      message: '请输入正确的邮箱格式'
    }
  },
  hobbies: {
    type: [String],
    enum: ['象棋', '乒乓球', '敲代码']
  },
  name: {
    type: String,
    // required: true,
    required: [true, '请填写姓名'],
    minlength: [2, '最少2个字符'],
    maxlength: [10, '最少10个字符'],
    trim: true
  },
  password: String,
  birthDay: {
    type: Date,
    default: Date.now
  }
})
const User = mongoose.model('User', userSchema)

function insertUser(obj) {
  new User(obj)
    .save()
    .then((result) => console.log('插入成功', result))
    .catch((e) => {
      const err = e.errors
      for (const key in err) {
        if (Object.hasOwnProperty.call(err, key)) {
          console.log('插入失败', err[key].message)
        }
      }
    })
}
// insertUser({ age: 30, name: ' x' })
insertUser({
  age: 30,
  email: '270628297qq.com',
  hobbies: ['象棋', '乒乓球', '敲代码', 'xxx'],
  name: '乐哥哥2',
  password: '888888'
})
function findUserBy(obj) {
  // 查询结果是一个对象，为空时返回null
  User.findOne(obj)
    .then((result) => {
      console.log('查询成功', result)
      console.log(result.birthDay.toLocaleString())
    })
    .catch((e) => console.log('查询失败', e))
}
// findUserBy({ name: '乐哥哥2' })
